import axios from 'axios'
import type { AxiosError, AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios'

export interface ApiResponse<Data = unknown> {
  [key: string]: any
  data?: Data
}

const http: AxiosInstance = axios.create({
  baseURL: '/API',
  timeout: 10000,
  withCredentials: false,
  headers: {
    'X-Requested-With': 'XMLHttpRequest'
  }
})

http.interceptors.request.use((config) => {
  return config
}, (error: AxiosError) => Promise.reject(error))

// 不处理任何业务 code，直接返回后端的原始数据
http.interceptors.response.use((response: AxiosResponse<ApiResponse>) => {
  return response.data as any
}, (error: AxiosError) => {
  const status = error.response?.status
  let message = '网络错误，请稍后再试'
  if (status) {
    if (status >= 500) message = '服务器开小差了，请稍后再试'
    else if (status === 404) message = '接口不存在(404)'
    else if (status === 401) message = '未授权或登录已过期(401)'
    else if (status === 403) message = '没有权限访问(403)'
  }
  return Promise.reject(new Error(message))
})

export function request<T = any>(config: AxiosRequestConfig) : Promise<T> {
  return http.request<any, T>(config)
}

export function get<T = any>(url: string, params?: Record<string, any>, config?: AxiosRequestConfig) : Promise<T> {
  return request<T>({ url, method: 'GET', params, ...(config || {}) })
}

export function post<T = any>(url: string, data?: any, config?: AxiosRequestConfig) : Promise<T> {
  return request<T>({ url, method: 'POST', data, ...(config || {}) })
}

export default http
